using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using NUnit.Framework;
using Universe.JRun;

namespace Universe.CrossIO.Test
{
    [TestFixture]
    public class TestMD5
    {
        private readonly HashAlgorithm Alg = HashAlgorithm.Create("MD5");

        [Test]
        public void Test()
        {
            JRunner jc = GetJMD5();
            using (MyTemp tmp = new MyTemp())
            {
                foreach (int size in MyEnvironment.Sizes)
                    ExecTest(size, tmp, jc);
            }
            
        }

        private JRunner GetJMD5()
        {
            return new JRunner("cldctest.MainMD5", MyEnvironment.ClassPath);
        }

        private void ExecTest(int size, MyTemp tmp, JRunner jc)
        {
            for (int sw = 0; sw < MyEnvironment.SourceWriters.Length; sw++)
            {
                // source stream
                string fileName = MyEnvironment.SourceWriters[sw].Method.Name + "_" + size + ".source";
                using (FileStream fs = new FileStream(tmp[fileName], FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    MyEnvironment.SourceWriters[sw](fs, size);
                }

                // .NET MD5
                byte[] netMD5 = null;
                using (FileStream fs = new FileStream(tmp[fileName], FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    netMD5 = this.Alg.ComputeHash(fs);
                }

                // J2ME MD5
                string nameJMD5 = Path.ChangeExtension(fileName, ".javamd5");
                JResponse res = jc.Run(tmp[fileName], tmp[nameJMD5]);
                Assert.AreEqual("", res.Errors, "Exec MD5");

                byte[] javaMD5 = null;
                using (FileStream fs = new FileStream(tmp[nameJMD5], FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    javaMD5 = new byte[fs.Length];
                    fs.Read(javaMD5, 0, javaMD5.Length);
                }


                bool areEquls = Convert.ToBase64String(netMD5) == Convert.ToBase64String(javaMD5);
                Assert.IsTrue(areEquls, "MD5 hash algorithm is fine");
            }
        }


    }
}
